﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SharpSvn;
using SharpSvn.Security;
using WebApplication.Core.Helpers;
using System.IO;

namespace WebApplication.Core
{
    public class Svn
    {
        public void Checkout(string svnUrl, string user, string password, long revision, string serverName, string applicationName)
        {
            string localPath = AppSettingsHelper.GetSrcPath + serverName + "(" + applicationName + ")";
            //if (Directory.Exists(localPath))
            //{
            //    string[] insideFolder = Directory.GetDirectories(localPath);
            //    try
            //    {
            //        foreach (string dir in insideFolder)
            //        {
            //            if (Path.GetFileName(dir) != ".svn")
            //                Directory.Delete(dir, true);
            //        }
            //    }
            //    catch (IOException io) { }//кастыль
            //}
            if (Directory.Exists(localPath))
                Directory.Delete(localPath, true);
            Directory.CreateDirectory(localPath);
            
            SvnUpdateResult sur;
            SvnCheckOutArgs args = new SvnCheckOutArgs();
         
            if(revision != 0)
                args.Revision = revision;
            using (SvnClient svn = new SvnClient())
            {
                try
                {
                    SvnUriTarget uri = new SvnUriTarget(svnUrl);
                    svn.Authentication.Clear();
                    svn.Authentication.DefaultCredentials = new System.Net.NetworkCredential(user, password);
                    svn.Authentication.SslServerTrustHandlers += delegate(object sendere, SvnSslServerTrustEventArgs ee) { ee.AcceptedFailures = ee.Failures; ee.Save = true; }; // Save acceptance to authentication store };
                    svn.CheckOut(uri, localPath, args, out sur);
                }
                catch (SvnException se)
                {
                    throw new Exception(se.Message);
                }
                catch (UriFormatException ue)
                {
                    throw new Exception(ue.Message);
                }
            }
        }
    }
}